package websocket

import (
	"context"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"websocket/internal/consts"
	"websocket/utility"
)

type wMessageFunc struct {
}

var (
	insMessageFunc = wMessageFunc{}
)

func MessageFunc() *wMessageFunc {
	return &insMessageFunc
}

type point struct {
	FromUnique    consts.WebsocketUniqueType `json:"from_unique"`
	ToUnique      consts.WebsocketUniqueType `json:"to_unique" v:"min:1"`
	MediumType    int                        `json:"medium_type" v:"in:0,1,2,3"`  //消息类型:0=文本,1=图片,2=视频,3=音频
	MediumContent string                     `json:"medium_content" v:"required"` //消息内容
	SendDatetime  string                     `json:"send_datetime"`
}

func (m *wMessageFunc) Point(ctx context.Context, work *consts.WebsocketWorkContext) (res *consts.WebsocketWorkRes, err error) {
	res = utility.Common.BuildWebsocketRes(ctx, work)
	res.Cmd = consts.WebsocketCmdMessagePoint
	var data *point
	err = work.Data.Scan(&data)
	if err != nil {
		res.Code = consts.WebsocketStatusErr
		res.Msg = err.Error()
		return
	}
	ok := g.Validator().Data(data).Run(ctx)
	if ok != nil {
		res.Code = consts.WebsocketStatusErrValidate
		res.Msg = ok.FirstError().Error()
		err = ok.FirstError()
		return
	}
	data.FromUnique = work.Unique
	if data.SendDatetime == "" {
		data.SendDatetime = utility.Common.BuildDatetime()
	}
	err = Manager().WriteMsg(ctx, data.ToUnique, Manager().BuildRes(ctx, &consts.WebsocketWorkRes{
		Cmd:    consts.WebsocketCmdMessagePoint,
		Code:   0,
		Msg:    "ok",
		Unique: data.ToUnique,
		Data:   data,
	}))
	if err != nil {
		res.Code = gerror.Code(err).Code()
		res.Msg = err.Error()
		res.Data = g.Map{
			"to_unique": data.ToUnique,
		}
		return
	}
	return
}
